package org.dromara.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.BusinessConfig;
import org.dromara.business.domain.bo.BusinessConfigBo;
import org.dromara.business.domain.vo.BusinessConfigVo;
import org.dromara.business.mapper.BusinessConfigMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.BusinessConfigCoreService;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.CacheUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 业务参数配置Service业务层处理
 *
 * @author zlj
 * @date 2024-05-19
 */
@RequiredArgsConstructor
@Service
public class BusinessConfigServiceImpl extends ServiceImpl<BusinessConfigMapper, BusinessConfig> implements BusinessConfigService, BusinessConfigCoreService {

    private final BusinessConfigMapper baseMapper;
    private final OssService ossService;

    /**
     * 查询业务参数配置
     */
    @Override
    public BusinessConfigVo queryById(Long businessConfigId) {
        return baseMapper.selectVoById(businessConfigId);
    }

    /**
     * 查询业务参数配置列表
     */
    @Override
    public TableDataInfo<BusinessConfigVo> queryPageList(BusinessConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusinessConfig> lqw = buildQueryWrapper(bo);
        Page<BusinessConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.setRecords(this.setUrl(result.getRecords()));
        return TableDataInfo.build(result);
    }

    /**
     * 查询业务参数配置列表
     */
    @Override
    public List<BusinessConfigVo> queryList(BusinessConfigBo bo) {
        LambdaQueryWrapper<BusinessConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BusinessConfig> buildQueryWrapper(BusinessConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusinessConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getConfigName()), BusinessConfig::getConfigName, bo.getConfigName());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), BusinessConfig::getConfigKey, bo.getConfigKey());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigValue()), BusinessConfig::getConfigValue, bo.getConfigValue());
        lqw.eq(bo.getSortNo() != null, BusinessConfig::getSortNo, bo.getSortNo());
        lqw.orderByAsc(BusinessConfig::getSortNo);
        return lqw;
    }

    /**
     * 新增业务参数配置
     */
    @Override
    @CacheEvict(cacheNames = CacheNames.BUSINESS_CONFIG, key = "#bo.configKey")
    public Boolean insertByBo(BusinessConfigBo bo) {
        BusinessConfig add = MapstructUtils.convert(bo, BusinessConfig.class);
        validEntityBeforeSave(add);
        return baseMapper.insert(add) > 0;
    }

    /**
     * 修改业务参数配置
     */
    @Override
    @CacheEvict(cacheNames = CacheNames.BUSINESS_CONFIG, key = "#bo.configKey")
    public Boolean updateByBo(BusinessConfigBo bo) {
        BusinessConfig update = MapstructUtils.convert(bo, BusinessConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusinessConfig entity) {

    }

    /**
     * 批量删除业务参数配置
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        for (Long id : ids) {
            BusinessConfig businessConfig = baseMapper.selectById(id);
            baseMapper.deleteById(id);
            CacheUtils.evict(CacheNames.BUSINESS_CONFIG, businessConfig.getConfigKey());
        }
        return true;
    }

    @Override
    public Boolean deleteWithValidByKeys(List<String> keys) {
        boolean remove = this.remove(Wrappers.<BusinessConfig>lambdaQuery().in(BusinessConfig::getConfigKey, keys));
        for (String key : keys) {
            CacheUtils.evict(CacheNames.BUSINESS_CONFIG, key);
        }
        return remove;
    }

    /**
     * 根据key获取业务参数配置详细信息
     *
     * @param configKey key
     */
    @Override
    @Cacheable(cacheNames = CacheNames.BUSINESS_CONFIG, key = "#configKey")
    public List<BusinessConfigVo> queryByKey(String configKey) {
        List<BusinessConfigVo> businessConfigVos = baseMapper.selectVoList(new LambdaQueryWrapper<BusinessConfig>()
            .eq(BusinessConfig::getConfigKey, configKey)
            .eq(BusinessConfig::getStatus, Constants.SUCCESS)
            .orderByDesc(BusinessConfig::getSortNo));
        return this.setUrl(businessConfigVos);
    }

    /**
     * 根据key获取业务参数配置详细信息
     *
     * @param configKey key
     */
    @Override
    public String queryValueByKey(String configKey) {
        return SpringUtils.getAopProxy(this).queryByKey(configKey).get(0).getConfigValue();
    }

    /**
     * 根据key获取单个业务参数配置详细信息
     *
     * @param configKey key
     */
    @Override
    public BusinessConfigVo queryOneByKey(String configKey) {
        return SpringUtils.getAopProxy(this).queryByKey(configKey).get(0);
    }

    private List<BusinessConfigVo> setUrl(List<BusinessConfigVo> businessConfigVos) {
        if (CollectionUtil.isNotEmpty(businessConfigVos)) {
            for (BusinessConfigVo record : businessConfigVos) {
                if (ObjectUtil.equals(record.getType(), "2")) {
                    record.setUrl(ossService.selectUrlByIds(record.getConfigValue()));
                }
            }
        }
        return businessConfigVos;
    }

    /**
     * 将经纬度解析为地址
     *
     * @param location gcj02坐标
     * @return 地址
     */
    @Override
    public String getAddress(String location) {
        String key = this.queryValueByKey("map");
        Map<String, Object> param = new HashMap<>();
        param.put("key", key);
        param.put("location", location);
        String response = HttpUtil.get("https://apis.map.qq.com/ws/geocoder/v1/", param);
        JSONObject result = JSONUtil.parseObj(response);
        Integer status = result.getInt("status");
        if (ObjectUtil.notEqual(status, 0)) {
            log.error("解析地址错误: 错误码: " + status + ", 错误信息: " + result.getStr("message"));
            throw new ServiceException("解析地址错误, 请联系管理员");
        }
        return result.getJSONObject("result").getStr("address");
    }

    @Override
    public boolean updateStatus(Long businessConfigId) {
        BusinessConfig config = this.getById(businessConfigId);
        config.setStatus(Objects.equals(config.getStatus(), "1") ? "0" : "1");
        boolean flag = this.updateById(config);
        CacheUtils.evict(CacheNames.BUSINESS_CONFIG, config.getConfigKey());
        return flag;
    }

    @Override
    public String selectNameByIds(String configIds) {
        List<String> list = new ArrayList<>();
        for (Long id : StringUtils.splitTo(configIds, Convert::toLong)) {
            BusinessConfigVo configVo = SpringUtils.getAopProxy(this).queryById(id);
            if (ObjectUtil.isNotNull(configVo)) {
                list.add(configVo.getConfigName());
            }
        }
        return String.join(StringUtils.SEPARATOR, list);
    }
}
